package routers

import (
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	_ "go-programming-tour-book/blog_service/docs" //初始化docs包
	"go-programming-tour-book/blog_service/global"
	"go-programming-tour-book/blog_service/internal/middleware"
	"go-programming-tour-book/blog_service/internal/routers/api"
	v1 "go-programming-tour-book/blog_service/internal/routers/api/v1"
	"go-programming-tour-book/blog_service/pkg/limiter"
	"net/http"
	"time"
)

var methodLimiters = limiter.NewMethodLimiter().AddBuckets(
	limiter.LimiterBucketRule{
		Key:          "/auth",
		FillInterval: time.Second,
		Capacity:     10,
		Quantum:      10,
	},
)

func NewRouter() *gin.Engine {
	r := gin.New()
	if global.ServerSetting.RunMode == "debug" {
		r.Use(gin.Logger())   //内部默认的中间件
		r.Use(gin.Recovery()) //内部默认的中间件
	} else {
		r.Use(middleware.AccessLog()) //自定义的日志中间件
		r.Use(middleware.Recovery())  //自定义的异常捕获中间件，在实际开发项目中，这类中间件应当尽可能地早注册
	}

	r.Use(middleware.RateLimiter(methodLimiters))                             //自定义的限流中间件
	r.Use(middleware.ContextTimeout(global.AppSetting.DefaultContextTimeout)) //自定义的超时控制中间件
	r.Use(middleware.Translations())                                          //自己创建的中间件
	r.Use(middleware.Tracing())                                               //自定义的追踪上下文中间件

	//接口文档
	url := ginSwagger.URL("http://127.0.0.1:8000/swagger/doc.json")
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url)) //注册一个针对 Swagger 的路由

	article := v1.NewArticle()
	tag := v1.NewTag()

	upload := api.NewUpload()
	r.POST("/upload/file", upload.UploadFile)
	r.StaticFS("/static", http.Dir(global.AppSetting.UploadSavePath))

	r.POST("/auth", api.GetAuth)

	apiV1 := r.Group("/api/v1")
	apiV1.Use(middleware.JWT())
	{
		//新增标签
		apiV1.POST("/tags", tag.Create)
		//删除指定标签
		apiV1.DELETE("/tags/:id", tag.Delete)
		//更新指定标签
		apiV1.PUT("/tags/:id", tag.Update)
		//更新指定标签的状态
		apiV1.PATCH("/tags/:id/state", tag.Update)
		//获取标签列表
		apiV1.GET("/tags", tag.List)

		//新增文章
		apiV1.POST("/articles", article.Create)
		//删除指定文章
		apiV1.DELETE("/articles/:id", article.Delete)
		//更新指定文章
		apiV1.PUT("/articles/:id", article.Update)
		//更新指定文章的状态
		apiV1.PATCH("/articles/:id/state", article.Update)
		//获取指定文章
		apiV1.GET("/articles/:id", article.Get)
		//获取文章列表
		apiV1.GET("/articles", article.List)
	}

	return r
}
